import { getUserFavoriteListAllForUser,postUserFavoriteEditForUser,postUserFavoritePlaceEditForUser,postUserFavoriteDeleteForUser } from '../../api/home'

Component({
  properties: {
    showAddPopup: Boolean,
    //地點
    place_id: {
      type: String,
      value: '' 
    },
  },
  data: {
    user_favorite_id: '',
    showSelectPopup: false,
    newFolderName: '',
    selectedFolder: '',
    collectModal:false,
    folderList: [] // 模擬的收藏夾
  },
  lifetimes: {
    created() {
      this.getCollect()
      
    }
  },
  methods: {
    async getCollect(){
      const res = await getUserFavoriteListAllForUser()
      this.setData({
        folderList:res.data.list
      })
    },
    // 輸入新收藏夾名稱
    onInputFolderName(e) {
      this.setData({ 
        newFolderName: e.detail.value,
        selectedFolder:''
       });
    },

    // 打開選擇收藏夾
    openSelectPopup() {
      this.getCollect()
      
      this.setData({ showSelectPopup: true });
    },

    // 關閉選擇收藏夾
    closeSelectPopup() {
      this.setData({ showSelectPopup: false });
    },

    // 選擇收藏夾
    chooseFolder(e) {
      this.setData({
        selectedFolder: e.currentTarget.dataset.name,
        user_favorite_id: e.currentTarget.dataset.user_favorite_id,
        newFolderName:'',
        showSelectPopup: false
      });
    },

    // 關閉添加收藏彈框
    closePopup() {
      this.setData({ 
        showAddPopup: false,
        collectModal: false,
       });
    },
    openClose(e){
      const id = e.currentTarget.dataset.id
      this.setData({
        user_favorite_id:id,
        collectModal: true,
      }) 
    },
    async confirmDelete(){
      const res = await postUserFavoriteDeleteForUser({
        user_favorite_id:this.data.user_favorite_id
      })
      wx.showToast({
        title: '刪除成功',
      })
      this.setData({
        collectModal:false
      })
      this.getCollect()
    },
    // 確認添加
    async confirmAdd() {
      const { newFolderName, selectedFolder } = this.data;
      if (!newFolderName && !selectedFolder) {
        wx.showToast({ title: '請輸入或選擇收藏夾', icon: 'none' });
        return;
      }
      // this.triggerEvent('confirm', {
      //   folder: newFolderName || selectedFolder
      // });
      // 创建收藏夹
      if(newFolderName){
        const res =await postUserFavoriteEditForUser({
          name:newFolderName
        })
        wx.showToast({
          title: '添加成功',
        })
      }
      if(selectedFolder){
        const res =await postUserFavoritePlaceEditForUser({
          user_favorite_id:this.data.user_favorite_id,
          place_id:this.properties.place_id
        })
        wx.showToast({
          title: '添加成功',
        })
        this.triggerEvent('refreshParent')
      }
      this.setData({
        newFolderName:'',
        selectedFolder:'',
      })
      this.closePopup();
    }
  }
});
